import * as types from './mutation-types'
import { indexApi, reportApi, allApi, userApi, loanOutApi } from '../api/api'
import Storage from '../utils/storage'
import { getBrowser, convertRequestURL, share } from '../utils/utils'
// import wx from 'weixin-js-sdk'
import parser from 'ua-parser-js'


const _parser = new parser();
const os = _parser.getOS().name
const windowHeight = $(window).height()
const windowWidth = $(window).width()
const screenHeight = window.screen.height
const screenWidth = window.screen.width

export const setDeviceId = ({ commit, state }, str ) => {
    commit(types.SET_DEVICEID, str)
    Storage.set('anniu_deviceId',str)
}
export const setshows = ({ commit, state }, str ) => {
    commit(types.SET_SHOWS, str)
    //Storage.set('anniu_deviceId',str)
}
export const setAuthIdImgs = ({ commit, state }, obj ) => {
    if(obj == 'remove'){
        commit(types.SET_AUTHIDIMGS, 'remove')
        Storage.set('pingguodai_authIdImgs',{})
        return
    }
    commit(types.SET_AUTHIDIMGS, obj)
    let authIdImgs = state.localInfo.authIdImgs
    let pos = obj.pos
    let result = obj.result
    authIdImgs[pos] = result
    Storage.set('pingguodai_authIdImgs',authIdImgs)
}

export const setNeedLogin = ({ commit, state }, boolean ) => commit(types.SET_NEEDLOGIN, boolean)

export const showLoading = ({ commit, state }, title) => commit(types.SHOW_LOADING, title)

export const hideLoading = ({ commit, state }) => {
  // setTimeout(() => {
    commit(types.HIDE_LOADING)
  // },0)
}

export const setScrollIn = ({ commit, state }, number) => commit(types.SET_SCROLLIN, number)

export const setScrollOut = ({ commit, state }, number) => commit(types.SET_SCROLLOUT, number)

export const setMsgTip = ({ commit, state },msgObj) => {
    let time = msgObj.time  || 1500
	let timer = setTimeout(() => {
 		commit(types.HIDE_MSGTIP)
	},time)
	msgObj.timer = timer
	commit(types.SET_MSGTIP, msgObj)
}

export const setShare = ({ commit, state },shareObj) => {
    share(shareObj.message,shareObj.timeline,shareObj.qq,)
}

export const showShare = ({ commit, state },shareObj) => {
    commit(types.SET_SHARE,true)
}
export const hideShare = ({ commit, state },shareObj) => {
    commit(types.SET_SHARE,false)
}

export const setMsgTipStyle = ({ commit, state },styleObj) => {
    commit(types.SET_MSGTIPSTYLE, styleObj)
}

export const setReportId = ({ commit, state },id) => {
    commit(types.SET_REPORTID, id)
}

/*---------*/
export const setlocalInfo = ({ commit, state },id) => {
    commit(types.SET_SHOWS, id)
}
// setSearchHistoryCurrentPage
// export const setLoginShow = ({ commit, state },boolean ) => {
//     commit(types.SET_LOGINSHOW, boolean)
// }

// setSearchHistoryCurrentPage
export const setLoanIndexRefresh = ({ commit, state },boolean ) => {
    commit(types.SET_LOANINDEXREFRESH, boolean)
}

export const setGoHome = ({ commit, state },boolean ) => {
    commit(types.SET_GOHOME, boolean)
}

// setLoanInForm
export const setLoanInUseForm = ({ commit, state }, object, remove ) => {
    commit(types.SET_LOANINUSEFORM, object, remove)
}
export const removeLoanInForm = ({ commit, state }, object ) => {
    commit(types.REMOVE_LOANINFORM, object)
}
export const setLoanInApplyForm = ({ commit, state }, object, remove ) => {
    commit(types.SET_LOANINAPPLYFORM, object, remove)
}

export const setLoanInPublishForm = ({ commit, state }, object, remove ) => {
    commit(types.SET_LOANINPUBLISHFORM, object, remove)
}

// setHasTradePassword
export const setHasTradePassword = ({ commit, state },boolean ) => {
    commit(types.SET_HASTRADEPASSWORD, boolean)
}

// setLoginPassword
export const setLoginPassword = ({ commit, state },password ) => {
    commit(types.SET_LOGINPASSWORD, password)
}

// setTransactionPassword
export const setTransactionPassword = ({ commit, state },password ) => {
    commit(types.SET_TRANSACTIONPASSWORD, password)
}

// setSessionId
export const setChannel = ({ commit, state }, channel ) => {
    commit(types.SET_CHANNEL, channel)
    Storage.set('channel',channel)
    // console.log(Storage.get('channel'))
}

// setBizRole
export const setBizRole = ({ commit, state }, bizRole ) => {
    commit(types.SET_BIZROLE, bizRole)
    let channel = Storage.get('channel')
    Storage.set(`youjie_${channel}_bizRole`,bizRole)
}

// setAdmin
export const setAdmin = ({ commit, state }, admin ) => {
	commit(types.SET_ADMIN, admin)
    Storage.set('admin',admin)
}

// setSessionId
export const setSessionId = ({ commit, state }, sessionId ) => {
    commit(types.SET_SESSIONID, sessionId)
    Storage.set(`pingguodai_sessionId`,sessionId)
    setHeaders({ commit, state })
}

export const setHeaders = ({ commit, state }) => {
    console.log('setHeaders start')
    let channel = state.localInfo.channel
    let sessionId = state.localInfo.sessionId
    let clientId = state.localInfo.clientId
    let deviceName = state.localInfo.deviceName
    let deviceId = state.localInfo.deviceId
    let geoLocation = state.localInfo.geoLocation
    $.extend($.ajaxSettings, {
        headers: {
            'clientId':clientId,
            'deviceCode':deviceId,
            'packageCode': 'h5.anniu.51sjd',
            'sourceName': channel,
            'deviceModel':deviceName,
            // 'X-Requested-With':'XMLHttpRequest',
            'appVersion':'1.0.0',
            'functionVersion':'00000000',
            'deviceType':'h5',
            'lat':geoLocation.lat,
            'lng':geoLocation.lng,
            'sessionId':sessionId,
        }
    })
    console.log('setHeaders finish')
}

// setReportInfo
export const setReportInfo = ({ commit, state } ) => {
    return reportApi.info()
    .then(result => {
        commit(types.SET_REPORTINFO, result)
    })
}

// setClientId
export const setClientId = ({ commit, state } ) => {
    setHeaders({ commit, state })
    return indexApi.bindClient()
    .then(result => {
        commit(types.SET_CLIENTID, result)
        Storage.set('pingguodai_clientId',result)
        setHeaders({ commit, state })
    })
}

// setClientId
export const setConfigInfo = ({ commit, state } ) => {
    return userApi.config({
        platform:'H5'
    })
    .then(result => {
        commit(types.SET_CONFIGINFO, result)
    })
}

// setClientId
export const storageGeoLocation = ({ commit, state }, now) => {
    if(navigator.geolocation) {
        navigator.geolocation.getCurrentPosition( (position) => {
            let lng = position.coords.longitude ;  
            let lat = position.coords.latitude ;  
            let params = {
                lng:lng,
                lat:lat,
                timestamp:now
            }
            console.log(params)
            commit(types.SET_GEOLOCATION, params)
            Storage.set('anniu_location',params)
            setHeaders({ commit, state })
        }, (error) => {
            let params = {
                lng:30.293835153529617,
                lat:120.10939208206689,
                timestamp:now
            }
            commit(types.SET_GEOLOCATION, params)
            Storage.set('anniu_location',params)
            setHeaders({ commit, state })
            switch(error.code) {   
                case error.PERMISSION_DENIED:   
                    console.error("定位失败,用户拒绝请求地理定位");   
                    break;   
                case error.POSITION_UNAVAILABLE:   
                    console.error("定位失败,位置信息是不可用");   
                    break;   
                case error.TIMEOUT:   
                    console.error("定位失败,请求获取用户位置超时");   
                    break;   
                case error.UNKNOWN_ERROR:   
                    console.error("定位失败,定位系统失效");   
                    break;   
            } 
        }) 
    }
}


// setGeoLocation

export const setGeoLocation = ({ commit, state } ) => {
    let timestamp = state.localInfo.geoLocation.timestamp
    let now = +new Date()
    let diff
    if(timestamp){
        diff = (now - timestamp) /1000 / 3600
        if(diff >= 24){
            storageGeoLocation({ commit, state },now)
        }
    }
    else{
        storageGeoLocation({ commit, state },now)
    }
}

// setClientId
export const setDeviceName = ({ commit, state } ) => {
    // let deviceDetailStr = 'iPhone 6 Plus'
    let deviceDetailStr = 'Other'
    let cpu

    let canvasSupport = !!document.createElement('canvas').getContext
    if(!canvasSupport) {
        cpu = 'Apple A9 GPU'
    }
    let canvas = document.createElement('canvas')
    let gl = canvas.getContext('experimental-webgl')
    let debugInfo = gl.getExtension('WEBGL_debug_renderer_info')
    if(debugInfo){
        cpu = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) 
    }
    if(os == 'iOS' && (screenWidth == 375 && screenHeight == 667 || screenWidth == 320 && screenHeight == 568 )){
        if(cpu == 'Apple A11 GPU') deviceDetailStr = 'iPhone 8'
        else if(cpu == 'Apple A10 GPU') deviceDetailStr = 'iPhone 7'
        else if(cpu == 'Apple A9 GPU') deviceDetailStr = 'iPhone 6s'
        else if(cpu == 'Apple A8 GPU') deviceDetailStr = 'iPhone 6'
        else deviceDetailStr = 'iPhone'
        commit(types.SET_DEVICENAME, deviceDetailStr)
        Storage.set('anniu_deviceName',deviceDetailStr)
        return
    }
    if(os == 'iOS' && (screenWidth == 414 && screenHeight == 736)){
        if(cpu == 'Apple A11 GPU') deviceDetailStr = 'iPhone 8 Plus'
        if(cpu == 'Apple A10 GPU') deviceDetailStr = 'iPhone 7 Plus'
        if(cpu == 'Apple A9 GPU') deviceDetailStr = 'iPhone 6s Plus'
        if(cpu == 'Apple A8 GPU') deviceDetailStr = 'iPhone 6 Plus'
        commit(types.SET_DEVICENAME, deviceDetailStr)
        Storage.set('anniu_deviceName',deviceDetailStr)

        return
    }
    if(os == 'iOS' && (screenWidth == 375 && screenHeight == 812)){
        if(cpu == 'Apple A11 GPU') deviceDetailStr = 'iPhone X'
        commit(types.SET_DEVICENAME, deviceDetailStr)
        Storage.set('anniu_deviceName',deviceDetailStr)

        return
    }
    if(os == 'iOS'){
        deviceDetailStr = 'iPhone'
        commit(types.SET_DEVICENAME, deviceDetailStr)
        Storage.set('anniu_deviceName',deviceDetailStr)
        return
    }
    if(os == 'Android'){
        deviceDetailStr = 'Android'
        commit(types.SET_DEVICENAME, deviceDetailStr)
        Storage.set('anniu_deviceName',deviceDetailStr)
        return
    }
    commit(types.SET_DEVICENAME, deviceDetailStr)
    Storage.set('anniu_deviceName',deviceDetailStr)

}





export const setUserInfo = ({ commit, state } ,object = {}) => {
    commit(types.SET_USERINFO, object)
}

// addPageNo
export const lendListSquare = ({ commit, state } ,object = {}) => {
    let channel = state.localInfo.channel
    let lendPageInfo = state.localInfo.lendPageInfo
    let lendList = state.localInfo.lendList
    let inPageInfo = lendPageInfo.inPageInfo
    let outPageInfo = lendPageInfo.outPageInfo
    let refresh = false
    let pageInfo = {
        outPageSize:60,
        inPageSize:20,
    }

    if(_.isEmpty(lendList) || object.action == 'next'){
        // console.log('haha')
        pageInfo.outPageNo = object.pageNum || 1
        pageInfo.inPageNo = 1
        refresh = true
    }
    else{
        if(inPageInfo.totalPage == inPageInfo.pageNum){
            let outPageNum = outPageInfo.pageNum + 1 > outPageInfo.totalPage ? 1 : outPageInfo.pageNum + 1
            let inPageNum = 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
            refresh = true
        }
        else if(inPageInfo.totalPage > inPageInfo.pageNum){
            // console.log(123)
            let outPageNum = outPageInfo.pageNum
            let inPageNum = inPageInfo.pageNum + 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
        }
    }
    return loanOutApi.lendListSquare(pageInfo)
    .then(result => {
        commit(types.SET_LENDPAGEINFO, result)
        Storage.set(`youjie_${channel}_lendPageInfo`,result)
        if(refresh){
            commit(types.SET_LENDLIST, result.inPageInfo.records)
        }
        else{
            let pageList = _.concat(lendList, result.inPageInfo.records) 
            commit(types.SET_LENDLIST, pageList)
        }
    })
}

export const borrowListSquare = ({ commit, state }, object ) => {
    let channel = state.localInfo.channel
    let borrowPageInfo = state.localInfo.borrowPageInfo
    let borrowList = state.localInfo.borrowList
    let inPageInfo = borrowPageInfo.inPageInfo
    let outPageInfo = borrowPageInfo.outPageInfo
    let refresh = false
    let filterStr = ''
    if(_.isEmpty(object.filterStr)) return
    else{
        filterStr = JSON.stringify(object.filterStr)
    }

    let pageInfo = {
        outPageSize:60,
        inPageSize:20,
        filterStr:filterStr
    }
    if(_.isEmpty(borrowList) || object.refresh){
        pageInfo.outPageNo = object.pageNum || 1
        pageInfo.inPageNo = 1
        refresh = true
    }
    else{
        if(inPageInfo.totalPage == inPageInfo.pageNum){
            let outPageNum = outPageInfo.pageNum + 1 > outPageInfo.totalPage ? 1 : outPageInfo.pageNum + 1
            let inPageNum = 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
            refresh = true
        }
        else if(inPageInfo.totalPage > inPageInfo.pageNum){
            console.log()
            let outPageNum = outPageInfo.pageNum
            let inPageNum = inPageInfo.pageNum + 1
            pageInfo.outPageNo = outPageNum
            pageInfo.inPageNo = inPageNum
        }
    }
    return loanOutApi.borrowListSquare(pageInfo)
    .then(result => {
        commit(types.SET_BORROWPAGEINFO, result)
        Storage.set(`youjie_${channel}_borrowPageInfo`,result)
        if(refresh){
            commit(types.SET_BORROWLIST, result.inPageInfo.records)
        }
        else{
            let pageList = _.concat(borrowList, result.inPageInfo.records) 
            commit(types.SET_BORROWLIST, pageList)
        }
    })
}


export const setLendFilterStr = ({ commit, state }, str) => commit(types.SET_LENDFILTERSTR, str)

export const setBorrowFilterStr = ({ commit, state }, str) => commit(types.SET_BORROWFILTERSTR, str)

export const setBorrowFilterObj = ({ commit, state }, obj) => commit(types.SET_BORROWFILTEROBJ, obj)

export const setRouterList = ({ commit, state }, router) => commit(types.SET_ROUTERLIST, router)

export const setRouterAnimation = ({ commit, state }, animationName ) => commit(types.SET_ROUTERANIMATION, animationName)

export const setSelectZIndex = ({ commit, state }, num ) => commit(types.SET_SELECTZINDEX, num)

export const setDocumentClick = ({ commit, state }, boolean ) => commit(types.SET_DOCUMENTCLICK, boolean)


export const setCity = ({ commit, state }, cityInfo ) => commit(types.SET_CITY, cityInfo)

export const setCarInfo = ({ commit, state }, info ) => commit(types.SET_CARINFO, info)

export const setCarCurrent = ({ commit, state }, info ) => commit(types.SET_CARCURRENT, info)

export const setUserId = ({ commit, state }, id) => commit(types.SET_USERID, id)

export const setCardPrice = ({ commit, state }, priceArr) => commit(types.SET_CARDPRICE, priceArr)

export const addCard = ({ commit, state }, card) => commit(types.ADD_CARD, card)

export const editCard = ({ commit, state }, index, card) => commit(types.EDIT_CARD, index, card)

export const deleteCard = ({ commit, state }, card) => commit(types.DELETE_CARD, card)

export const setBaodanresult = ({ commit, state }, result) => commit(types.SET_BAODANRESULT, result)

export const removeBaodanresult = ({ commit, state }, result) => commit(types.REMOVE_BAODANRESULT, result)

export const setIndexViewForm = ({ commit, state }, form) => commit(types.SET_INDEXVIEWFORM, form)

export const setUpdateDashboard = ({ commit, state }, boolean ) => commit(types.SET_UPDATEDASHBOARD, boolean)

export const setDashboard = ({ commit, state }, dashboard ) => commit(types.SET_DASHBOARD, dashboard)

export const setRequestParams = ({ commit, state }, requestparams ) => commit(types.SET_REQUESTPARAMS, requestparams)

export const setAuthType = ({ commit, state }, type ) => commit(types.SET_AUTHTYPE, type)


